/**
 * created by zhouli on 2018/7/10
 * 通用 table 类型报表
 * 1.通过报表详情-初始化搜索组件，初始化表格显示字段
 * 2.依赖项搜索组件特殊处理
 * 3.一个特殊报表，id为12，界面稍微不一样，特殊处理
 */
import React from 'react';
import { connect } from 'react-redux';
import { Button, Icon, message, Spin, Popover, Modal, Tooltip } from 'antd';
import menuRoute from 'routes/menuRoute';
import TRService from 'containers/data-center/report/travel-report/travel-report.service';
import SearchArea from 'components/search-area';
import ExportModal from 'components/template/export-modal/export-modal';
import "styles/data-center/report/travel-report/travel-report.scss";
import { deepFullCopy, messages } from "share/common";
import moment from 'moment';
import ExpenseTypeSelectForReport
  from 'containers/data-center/report/travel-report/components/expense-type-select-for-report/expense-type-select-for-report';
import CostCenterSelectForReport
  from 'containers/data-center/report/travel-report/components/cost-center-select-for-report/cost-center-select-for-report';
import ReportTypeWithVendor
  from 'containers/data-center/report/travel-report/components/report-type-with-vendor/report-type-with-vendor';
import CompanySelectForReport
  from 'containers/data-center/report/travel-report/components/company-select-for-report/company-select-for-report';
import BorrowerSelectForReport
  from 'containers/data-center/report/travel-report/components/borrower-select-for-report/borrower-select-for-report';
import CostCenterItemSelectForReport
  from 'containers/data-center/report/travel-report/components/cost-center-item-select-for-report/cost-center-item-select-for-report';
import CurrencySelectForReport
  from 'containers/data-center/report/travel-report/components/currency-select-for-report/currency-select-for-report';
import ResizeTable from 'components/resize-table'
import TravelModal from 'containers/data-center/report/travel-report/travel-modal';
import TravelGiftModal from 'containers/data-center/report/travel-report/travel-gift-modal';

class TravelReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cardData: {},
      loading: true,
      loadingSearchArea: true,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchFormExtraFieldsArr: [],
      //额外的搜索参数，依赖，主要用来控制依赖的参数是否显示与可用等
      extraFieldsSearchParams: {
        setOfBooksId: null,
        payee_type: null
      },
      //搜索区：特殊字段，额外添加
      extraFieldsSearchArea: [],
      //特殊字段，选择之后的值
      extraFieldsValues: {
        // 注意选择之后的值，对应的key是 cost ，但是上传的时候不一定是 cost，
        // 可能是 cc1,需要在查询的时候去根据后端字段改变
        cost: undefined,
        expense_type: undefined,
        cost_center_code: undefined
      },
      reportDetail: {},
      //搜索区字段：根据后端定
      searchForm: [],
      //搜索传参：根据后端定
      params: {},
      //列名：根据后端定
      columns: [],
      //报表数据
      data: [],
      // 用于保存额外搜索参数的组件实例
      extraFieldsRefs: {},
      visible: false,
      modalBusinessCode: undefined,
      modalTitle: undefined,
      giftVisible: false,
      giftModalBusinessCode: undefined,
      giftModalTitle: undefined,
      modalInvoiceOid: undefined
    }
  }

  componentDidMount() {
    /*
    * 初始化搜索组件之前，需要的数据先请求出来
    * */
    TRService.InitSearchComponents(this.props.language.code)
      .then((res) => {
        this.getReportDetail(this.props.params.id);
      })
  }

  /*
  * 特殊报表 id==12
  * 获取 审批流程平均时长
  * */
  getApproverTime(request) {
    TRService.getApproverTime(request)
      .then((res) => {
        this.setState({
          cardData: res.data
        })
      })
  }

  /*
   * 特殊报表 id==33
   * 获取 待审批单据数量 & 平均待审批时长
   * */
  getWaitingTime(request) {
    TRService.getWaitingTime(request).then(res => {
      this.setState({
        cardData: res.data
      });
    });
  }

  /*
  * 获取表详细结构
  * 并且根据响应去初始化搜索组件
  * */
  getReportDetail(reportId, noSearch, callback, searchParams) {
    this.setState({
      loadingSearchArea: true
    });
    console.log("searchParams", searchParams)
    TRService.getReportDetail(reportId, searchParams, (data) => {
      this.showModal(data);
    })
      .then((res) => {
        /*
        * res.data.extraFieldsSearchArea 返回空数组[]
        * 或者如下结构
         [
           {
            criteriaCode: "cost"
            criteriaName: "成本中心"
            criteriaPropName: "cc"
            criteriaSeqNo: "3"
            dependecyCriteriaCode: "books"
           }
         ]
        * */
        let { searchFormByMan, paramsByMan, setColumnByMan } = res.data;
        console.log('setColumnByMan', setColumnByMan)
        // https://pmo.mcd.com.cn/jira/browse/TES-896
        if (parseInt(this.props.params.id) === 51) {
          setColumnByMan.map(item => {
            if (item.columnDisplayName === '参与人数量') {
              item.render = (text, record, index) => {
                // console.log('text', text, record)
                return text > 0 ? <Tooltip title={text}>
                  <span onClick={() => this.onOpenModal(record, '参与人信息')} style={{ color: '#1890ff', cursor: 'pointer' }}>{text}</span>
                </Tooltip> : '-'
              }
            }
            if (item.columnDisplayName === '费用参与人员') {
              item.render = (text, record, index) => {
                // console.log('text', text, record)
                return text > 0 ? <Tooltip title={text}>
                  <span onClick={() => this.onOpenModal(record, '报销单参与人员')} style={{ color: '#1890ff', cursor: 'pointer' }}>{text}</span>
                </Tooltip> : '-'
              }
            }
          })
        }
        if (parseInt(this.props.params.id) === 36) {
          setColumnByMan.map(item => {
            if (item.columnDisplayName === '申请单接收人员') {
              item.render = (text, record, index) => {
                // console.log('text', text, record)
                return text > 0 ? <Tooltip title={text}>
                  <span onClick={() => this.onOpenGiftModal(record, '申请单接收人员信息')} style={{ color: '#1890ff', cursor: 'pointer' }}>{text}</span>
                </Tooltip> : '-'
              }
            }
            if (item.columnDisplayName === '报销单接收方人员') {
              item.render = (text, record, index) => {
                // console.log('text', text, record)
                return text > 0 ? <Tooltip title={text}>
                  <span onClick={() => this.onOpenGiftModal(record, '报销单接收人信息')} style={{ color: '#1890ff', cursor: 'pointer' }}>{text}</span>
                </Tooltip> : '-'
              }
            }
          })
        }
        if (searchParams && (parseInt(this.props.params.id) === 53 || parseInt(this.props.params.id) === 52)) {
          searchFormByMan[0].defaultValue = searchParams.date && searchParams.date !== 'Invalid date' ? moment(searchParams.date) : undefined;
          searchFormByMan[1].defaultValue = searchParams.gm_name ? searchParams.gm_name : undefined;
          searchFormByMan[2].defaultValue = searchParams.gm_cost_center ? searchParams.gm_cost_center : undefined;
        }
        this.setState({
          reportDetail: res.data,
          searchForm: searchFormByMan,
          params: searchParams ? searchParams : paramsByMan,
          columns: setColumnByMan,
          loadingSearchArea: false
        }, () => {
          //自动触发搜索账套改变时间，设置依赖项的初始值
          let val = TRService.getBooksDefaultValueById("books", this.state.searchForm);
          this.eventSearchAreaHandle('books', val, "man");
          if (this.state.columns.length === 0) {
            /*
            * 有个字段设置按钮，点击进入，可以把报表列的字段隐藏，或者显示
            * 如果全部隐藏了，就没法显示数据，这里就提示一下
            * */
            message.warning(messages('data-center.key49')/*字段全被隐藏，请点击[字段设置]，设置字段显示。*/)
          }
          /*
          * 上面的逻辑去初始化搜索组件，但是还有一些特殊的组件需要额外加入
          * 比如有些依赖账套的组件、有级联的搜索组件，就在这里加
          * */
          this.setExtraFieldsByRes(this.state.reportDetail, () => {
            let params = TRService.setDefaultTime(this.state.searchForm);
            if (!noSearch) {
              /*
              * 不是人为点击搜索，默认进入页面，就需要搜索一次
              * */

              /**
               * 这处理值的逻辑真是要把我。。。。
               */
              if (Number(reportId) === 15) {
                params['receipt_date'] = this.state.params['receipt_date'];
              }

              this.handleSearch(params);
            }
            if (callback) {
              callback();
            }
          });
        })
      })
  }

  // 保存额外搜索参数的组件实例，用于清空操作
  onBindExtraFieldsRefs = ({key, value}) => {
    let { extraFieldsRefs } = this.state;
    extraFieldsRefs[key] = value;
    this.setState({
      extraFieldsRefs
    })
  };

  /*
  * 通过后端的 code，设置是否显示额外的搜索组件到 searchArea
  * searchArea 默认情况无法支持配置，相当于一只外挂搜索组件挂到 searchArea 组件里面
  * 有依赖的搜索组件，设置好，进入回调
  * */
  setExtraFieldsByRes = (reportDetail, callback) => {
    //有依赖项
    if (reportDetail.extraFieldsSearchArea.length > 0) {
      //可能显示字段（这些字段都会有依赖）
      let searchFormExtraFieldsArrMaybe = [
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "report_type_add_vendor",//
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <ReportTypeWithVendor
              multiple={true}
              title={messages('data-center.key127')/*报销类型*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmReportTypeWithVendor}
              onConfirm={this.onConfirmReportTypeWithVendor}
            />
          )
        },
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "company",//还款单报表依赖
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <CompanySelectForReport
              multiple={true}
              title={messages('data-center.key107')/*选择公司*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmCompany}
              onConfirm={this.onConfirmCompany}/>
          )
        },
        // 币种
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "currency",//还款单报表依赖
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <CurrencySelectForReport
              title={messages('common.currency')/*币种*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmCurrency}
              onConfirm={this.onConfirmCurrency}/>
          )
        },
        // 借款方，可以选择人或者供应商
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "borrower",//还款单报表依赖
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <BorrowerSelectForReport
              title={messages('data-center.key108')/*借款方*/}
              payee_type={this.state.extraFieldsSearchParams.payee_type}
              onCancel={this.onConfirmBorrower}
              onConfirm={this.onConfirmBorrower}/>
          )
        },
        // 成本中心项
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "cost",//
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <CostCenterItemSelectForReport
              title={messages('data-center.key31')/*成本中心项*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmCostCenterItem}
              onConfirm={this.onConfirmCostCenterItem}/>
          )
        },
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "cost_center_code",//
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <CostCenterSelectForReport
              title={messages('data-center.key30')/*成本中心*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmCostCenter}
              onConfirm={this.onConfirmCostCenter}/>
          )
        },
        // 费用类型
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "expense_type",
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <ExpenseTypeSelectForReport
              multiple={true}
              title={messages('common.expense.type')/*费用类型*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmExpenseType}
              onConfirm={this.onConfirmExpenseType}
              onRef={this.onBindExtraFieldsRefs}/>
          )
        },
      ];
      //通过后端返回的依赖字段，去 searchFormExtraFieldsArrMaybe 数组里面找到对应的字段
      let searchFormExtraFieldsArr = [];
      let reportDetail = this.state.reportDetail;
      reportDetail.extraFieldsSearchArea.map(item => {
        let field = TRService.findRightDependecyField(item, searchFormExtraFieldsArrMaybe);
        field.id = item.criteriaPropName;
        field.label = item.criteriaName;
        field.seqNo = item.criteriaSeqNo;
        searchFormExtraFieldsArr.push(field);
      });
      this.setState({
        searchFormExtraFieldsArr,
        //额外的扩展字段
        extraFieldsSearchArea: searchFormExtraFieldsArr.map(item => {
          return {
            filed: item.getField,
            seqNo: item.seqNo
          }
        }),
      }, () => {
        callback && callback();
      })
    } else {
      callback && callback();
    }
  }
  /*
  * 针对 id 为 12 的效率报表
  * 报表数据是可以点击的，其他报表是不能点击的
  * 这里点击进行详情报表 id 13; 详情页面就是当前页面，所以里面只需要重新请求数据
  * */
  rowDetail = (e, record) => {
    let approverOid = record.approverOid;
    let approveUser = record.approver;
    let { params } = this.state;
    let approval_time = params.approval_time;
    //这边跳转到当前页面，路由id变为 13，查询一样的条件，把审批人，oid带入查询条件
    let path = menuRoute.getRouteItem('travel-report', 'key').url.replace(':id', 13);
    this.props.params.id = 13;
    this.getReportDetail(this.props.params.id, true, () => {
      this.getTravelDataList(approverOid, approval_time, approveUser)
    });
    this.context.router.push(path);
  };

  /*
  * 获取报表数据，查询
  * 获取数据的时候，有个也是的详情报表 id 为 13 的需要注意 ，此时参数有 approverOid
  * */
  getTravelDataList(approverOid, approval_time, approveUser) {
    this.setState({ loading: true });
    let { params, pagination, columns, searchForm, searchFormExtraFieldsArr, extraFieldsValues } = this.state;
    //需要写函数去匹配：目前只考虑成本中心
    if (searchFormExtraFieldsArr.length > 0) {
      searchFormExtraFieldsArr.map(item => {
        if (item.backend_id === "company") {
          //借款人 员工费用类型汇总趋势表 有依赖
          params[item.id] = extraFieldsValues.company;
        }
        if (item.backend_id === "report_type_add_vendor") {
          //员工费用类型汇总趋势表 有依赖
          params[item.id] = extraFieldsValues.report_type_add_vendor;
        }
        if (item.backend_id === "currency") {
          //借款人 有依赖
          params[item.id] = extraFieldsValues.currency;
        }
        if (item.backend_id === "borrower") {
          //仅仅是针对还款单报表,还款单报表id19 有依赖
          //借款人有依赖
          params[item.id] = extraFieldsValues.borrower;
        }
        if (item.backend_id === "cost") {
          params[item.id] = extraFieldsValues.cost;
        }
        if (item.backend_id === "expense_type") {
          params[item.id] = extraFieldsValues.expense_type;
        }
        if (item.backend_id === "cost_center_code") {
          if (extraFieldsValues.cost_center_code && extraFieldsValues.cost_center_code.length) {
            params[item.id] = extraFieldsValues.cost_center_code.map(item => {
              return item.code;
            });
            params[item.id] = JSON.stringify(params[item.id]);
          }
        }
      })
    }
    if (approverOid) {
      params.approver_oid = JSON.stringify([approverOid]);
      params.approval_time = approval_time;
      let sy = parseInt(JSON.parse(approval_time)[0].split('-')[0]),
        sm = parseInt(JSON.parse(approval_time)[0].split('-')[1]) - 1,
        ey = parseInt(JSON.parse(approval_time)[1].split('-')[0]),
        em = parseInt(JSON.parse(approval_time)[1].split('-')[1]) - 1;
      let s = moment(new Date(sy, sm, 1)), e = moment(new Date(ey, em, 1));
      searchForm[0].defaultValue = s;
      searchForm[1].defaultValue = e;
      //填充审批人oid
      searchForm.map(item => {
        if (item.id === 'approver_oid') {
          item.defaultValue = [
            {
              userOID: approverOid,
              fullName: approveUser
            }
          ]
        }
      });
      this.setState({
        searchForm
      })
    } else {
      //清除填充审批人oid
      searchForm.map(item => {
        if (item.id === 'approver_oid') {
          item.defaultValue = undefined
        }
      });
      this.setState({
        searchForm
      })
    }
    // 费用明细报表不处理
    if (params['form_oid'] && Number(this.props.params.id) !== 3) {
      params['form_oid'] = JSON.stringify(params['form_oid'].split(','))
    }
    if (params['date'] == 'Invalid date') {
      params['date'] = undefined;
    }
    let request = {
      id: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
      criteria: params
    };
    if (parseInt(this.props.params.id) === 12) {
      //审批效率报表，特殊处理
      this.getApproverTime(request);
      if (!(columns.length && columns.length > 1 && columns[columns.length - 1]._isAdd)) {
        /*
        * 审批效率报表，特殊处理
        * 如果已经添加，则不添加
        * */
        columns.push(
          {
            fixed: 'right',
            width: 100,
            title: messages('common.operation')/*操作*/,
            _isAdd: true,
            render: (text, record) => (<span>
              <a onClick={(e) => this.rowDetail(e, record)}>
                {messages("common.detail")}
              </a>
            </span>)
          }
        );
      }
    } else {
      //如果不是 效率报表 12，被添加过操作列，则删除
      if (columns.length && columns.length > 1 && columns[columns.length - 1]._isAdd) {
        columns.pop();
      }
    }
    //待审批效率报表的特殊处理
    if (parseInt(this.props.params.id) === 33) {
      this.getWaitingTime(request);
    }
    TRService.getTravelDataList(request)
      .then((res) => {
        pagination.total = Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0;
        this.setState({
          columns,
          data: res.data,
          loading: false,
          pagination
        })
      })
      .catch(() => {
        this.setState({
          loading: false,
        })
      })
  }

  //费用类型 确认
  onConfirmExpenseType = (val) => {
    this.onEventHandlerByType(val, 'expense_type')
  };
  //币种确认
  onConfirmCurrency = (val) => {
    this.onEventHandlerByType(val, 'currency')
  };
  //借款方确认
  onConfirmBorrower = (val) => {
    this.onEventHandlerByType(val, 'borrower')
  };
  //报销单状态
  onConfirmReportTypeWithVendor = (val) => {
    this.onEventHandlerByType(val, 'report_type_add_vendor')
  };
  //公司确认
  onConfirmCompany = (val) => {
    this.onEventHandlerByType(val, 'company')
  };
  //成本中心项确认
  onConfirmCostCenterItem = (val) => {
    this.onEventHandlerByType(val, 'cost')
  };
  //成本中心确认
  onConfirmCostCenter = (val) => {
    this.onEventHandlerByType(val, 'cost_center_code')
  };
  //设置额外搜索组件值
  onEventHandlerByType = (val, tyle) => {
    let { extraFieldsValues } = this.state;
    extraFieldsValues[tyle] = val;
    this.setState({
      extraFieldsValues
    })
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getTravelDataList();
    })
  };

  //检测是否有这个参数
  _checkHasParam = (searchForm, type) => {
    let len = searchForm.length;
    for (let i = 0; i < len; i++) {
      let item = searchForm[i];
      if (item.backend_id === type) {
        return true;
      }
    }
    return false;
  }
  //清空搜索
  clearSearchHandle = () => {
    let { extraFieldsSearchParams, extraFieldsValues, params, searchForm, extraFieldsRefs } = this.state;
    const reportId = Number(this.props.params.id);
    Object.assign(extraFieldsSearchParams, {
      setOfBooksId: undefined,
      payee_type: undefined,
      company: undefined,
      cost: undefined,
      expense_type: undefined,
      cost_center_code: undefined,
    })
    for (let key in params) {
      params[key] = "";
    }
    params = TRService.setDefaultTime(searchForm);
    let val = TRService.getBooksDefaultValueById("books", searchForm);
    if (val.length > 0 && val[0].setOfBooksId) {
      extraFieldsSearchParams.setOfBooksId = val[0].setOfBooksId;
      if (this._checkHasParam(searchForm, 'books')) {
        params['set_of_books_id'] = val[0].setOfBooksId;
      }
    }
    if (this._checkHasParam(searchForm, 'year')) {
      params['YEAR'] = (new Date()).getFullYear();
    }

    if (reportId === 15) {  // 发票汇总报表默认时间
      let { currentTime, currentTimeBeforeThree } = TRService.getCurrentTime();
      params["receipt_date"] = [currentTimeBeforeThree, currentTime];
    }

    for (let key in extraFieldsRefs) {
      let ref = extraFieldsRefs[key];
      ref && ref.handleCancel && ref.handleCancel();
    }

    this.setState({
      extraFieldsSearchParams,
      params,
    }, () => {
      this.setExtraFieldsByRes(this.state.reportDetail, () => {
        this.handleSearch(this.state.params);
      });
    })
  };

  /*
  * 校验数据
  * 执行点击搜搜索
  * */
  handleSearch = (values) => {
    const {
      isNeedBooksRequest,
      getNeedCheckFields,
      getNeedCheckFieldsSlave,
      checkDateValueIsNull,
      checkDateValueStartEnd,
      checkDateValueStartEndSlave,
      checkDateValueGap,
      checkDateDuration
    } = TRService;
    if (isNeedBooksRequest(this.state.reportDetail) &&
      (!values.set_of_books_id || values.set_of_books_id.length === 0) &&
      !this.state.params['set_of_books_id']) {
      message.warn(messages('data-center.key136')/*账套不能为空*/);
      return;
    }
    let dateFields = getNeedCheckFields(values);
    //这种时间类型只需检查开始不能大于开始
    let dateFieldsSlave = getNeedCheckFieldsSlave(values);
    // $# 新增非必输
    const filterRequrie=['card_issuing_time']
    if (checkDateValueIsNull(dateFields, values)&&!dateFields.some(item=>filterRequrie.includes(item))) {
      message.warn(messages('data-center.key16'/*请选择时间*/));
      return;
    }
    if (checkDateValueStartEnd(dateFields, values) || checkDateValueStartEndSlave(dateFieldsSlave, values)) {
      message.warn(messages('data-center.key17'/*开始时间须小于结束时间*/));
      return;
    }
    if (checkDateValueGap(dateFields, values)) {
      message.warn(messages('data-center.key91')/*查询时间跨度不能超过12个月*/);
      return;
    }
    let needArrParam = {};

    const { params } = this.props;
    const REPORT_ID = Number(params.id);
    console.log('values', values)
    for (let key in values) {
      let item = values[key],
        receiptDateItem,  // 开票日期项
        createTimeItem; // 费用发生日期项

      if (REPORT_ID === 15 && key === 'receipt_date' || key === 'expense_created_date') {// 发票汇总报表费用发生日期跟开票日期有联动判断
        receiptDateItem = values['receipt_date'] || [];
        createTimeItem = values['expense_created_date'] || [];
        let [createTimeStart, createTimeEnd] = createTimeItem;
        let [receiptDateStart, receiptDateEnd] = receiptDateItem;
        // if (!createTimeStart && !createTimeEnd && !receiptDateStart && !receiptDateEnd) { // 都未填则提示选择费用发生日期
        //   message.warn(messages('data-center.key145')/*请选择费用发生日期！*/);
        //   return;
        // }

      // bug 2146,取消日期限制
      /*  if (!receiptDateStart && !receiptDateEnd) { // 开票日期未填的情况下
          if (checkDateDuration(createTimeStart, createTimeEnd)) {
            message.warn(messages('data-center.key91')/!*查询时间跨度不能超过12个月*!/);
            return;
          }
        } else {  // 开票日期不为空时，均超过12个月才提示
          if (checkDateDuration(receiptDateStart, receiptDateEnd) && checkDateDuration(createTimeStart, createTimeEnd)) {
            message.warn(messages('data-center.key91')/!*查询时间跨度不能超过12个月*!/);
            return;
          }
        }*/
      }

      if (item && item.constructor && item.constructor.name === "Array") {
        /*
        * 支持多选
        * task 25884
        * 每一行代表一个选择器，多个参数
        * 支持多选，且传字符串数组
        * */
        let supportMultipleArr = [
          'reimb_status',//报销单状态
          'inv_check_result', 'check_result',//发票检验结果  发票检验结果返回码  两个查询参数对应一个搜索器
          'receipt_type_no',//发票类型
          'company_oid', 'applicant_company_oid',//公司
          'department_code', 'applicant_dept_code', 'department_name',//部门
          'expense_dept_number', // 费用承担部门
          'receipt_label_types',//发票标签
          'applicant_oid', 'rejecter_oid', 'approver_oid',//申请人
          'collector',  // 收单人
          'report_type_add_vendor', 'form_oid',//带供应商的报销类型code
          'report_status_add_vendor', 'status',//带供应商的报销状态code
          'label_code', 'label_types', // 单据标签
          'card_type_code', //卡券类型
          'invoice_type_code', //发票类型
          'cost_bearing_company_oid', //费用承担公司
          'employee_oid', //乘车人
        ];

        let dateRangeArr = [
          'receipt_date', // 收单日期 或 开票日期
          'receive_date', // 收单日期
          'expense_receipt_date', // 开票日期
          'reimb_submitted_date', // 单据提交日期
          'create_time',  // 费用发生日期
          'expense_created_date',  // 费用发生日期
          'single_date',
          'date'
        ];

        if (dateRangeArr.includes(key)) {
          if (item.length) {
            needArrParam[key] = JSON.stringify(item.map(date => {
              let result = moment(date).format("YYYY-MM-DD");
              return result !== "Invalid date" ? result : null
            }));
          } else {
            needArrParam[key] = "[null,null]"
          }
          continue;
        }

        if (supportMultipleArr.includes(key)) {
          needArrParam[key] = JSON.stringify(item);
        } else {
          /*
          * 这些不支持传数组，所以下面取第一个
          *
          * 这个逻辑真是把我看懵了。。。
          * */
          values[key] = item[0]
        }
      }
    }
    let { pagination, searchForm } = this.state;
    pagination.page = 0;
    pagination.current = 1;
    //这个地方用deepCopy，只是因为在子组件要监听nextProps变化
    let v = deepFullCopy(values);
    let _params = TRService.transDateToArr(v, searchForm, TRService.getNeedCheckFields(v), TRService.getNeedCheckFieldsSlave(v));
    let _paramsT = TRService.tansYearMonth(_params, this.state.searchForm);
    let paramsT = Object.assign(_paramsT, needArrParam);
    this.setState({
      pagination,
      params: Object.assign(this.state.params, paramsT)
    }, () => {
      if ((parseInt(this.props.params.id) === 53 || parseInt(this.props.params.id) === 52)) {
        this.getReportDetail(this.props.params.id, true, () => {
          this.getTravelDataList()
        }, Object.assign(this.state.params, paramsT));
      } else {
        this.getTravelDataList()
      }
    })
  };

  //设置表结构
  goToSetting = () => {
    let path = menuRoute.getRouteItem('travel-report-setting', 'key').url.replace(':id', this.props.params.id);
    this.context.router.push(path);
  }

  //返回到列表
  handleBack = () => {
    let path = menuRoute.getRouteItem('report', 'key').url;
    this.context.router.push(path);
  };

  //当搜索自动发送改变
  eventSearchAreaHandle = (e, item, type) => {
    let { extraFieldsSearchParams, extraFieldsValues } = this.state;

    if (e === "books") {
      /*
      * 如果账套发送改变，则依赖账套的搜索器就需要重新选择
      * 值需要清空
      * */
      if (type !== 'man') {
        message.warn(messages('data-center.key129')/*请重选依赖账套的搜索条件*/)
      }
      Object.assign(extraFieldsValues, {
        expense_type: undefined,
        cost: undefined,
        cost_center_code: undefined,
      });
      extraFieldsSearchParams.setOfBooksId = null;
      if (item.length > 0 && item[0].setOfBooksId) {
        extraFieldsSearchParams.setOfBooksId = item[0].setOfBooksId;
      }
      this.setState({
        extraFieldsValues,
        extraFieldsSearchParams
      }, () => {
        this.setExtraFieldsByRes(this.state.reportDetail);
      })
    }
    if (e === "payee_type") {
      //事件没加上
      extraFieldsSearchParams.payee_type = item;
      this.setState({
        extraFieldsValues,
        extraFieldsSearchParams
      }, () => {
        this.setExtraFieldsByRes(this.state.reportDetail);
      })
    }
  }

  renderSearchArea() {
    let { extraFieldsSearchArea, searchForm, loadingSearchArea, loading } = this.state;
    const { params }  = this.props;
    if (loadingSearchArea) {
      return (
        <div className="loading-container">
          <Spin tip={messages('data-center.key19'/*正在初始化查询参数*/)}//正在初始化查询参数
                size="large"/>
        </div>
      )
    } else {
      return (
        <SearchArea
          eventHandle={this.eventSearchAreaHandle}
          sorted={true}
          extraFieldsSorted={extraFieldsSearchArea}
          searchForm={searchForm}
          clearHandle={this.clearSearchHandle}
          submitHandle={this.handleSearch}
          loading={loading}
          reportId={params.id}/>
      )
    }
  }

  renderReportTable() {
    let { pagination, data, columns, loading, loadingSearchArea } = this.state;
    if (loadingSearchArea) {
      return (
        <div className="loading-container">
          <Spin tip={messages('data-center.key20'/*正在初始化报表列*/)}
                size="large"/>
        </div>
      )
    } else {
      return (
        <ResizeTable
          scroll={{ x: columns.length * 200 }}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={this.onChangePager}
          columns={columns}
          size="middle"
          bordered/>
      )
    }
  }

  /*
  * id == 12特殊组件 id == 33特殊组件
  * */
  renderCards = () => {
    let { cardData } = this.state;
    let { params } = this.props;
    if (parseInt(params.id) === 12) {
      return <div className='card-ward'>
        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('data-center.key44')/*处理单据数量*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.processedNumber}</h2>
          </div>
        </div>

        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('data-center.key45')/*审批节点平均时长*/}
            </div>
            <div className='tips f_right'>
              <Popover content={messages('data-center.key46')/*自动审批节点不纳入数据统计*/}>
                <Icon type="info-circle"/>
              </Popover>
            </div>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.documentAverageApprovalTime}</h2>
          </div>
        </div>

        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('data-center.key47')/*流程平均审批节点数*/}
            </div>
            <div className='tips f_right'>
              <Popover content={messages('data-center.key46')/*自动审批节点不纳入数据统计*/}>
                <Icon type="info-circle"/>
              </Popover>
            </div>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.averageNodeNumber}</h2>
          </div>
        </div>

        <div className='card-item last-card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('data-center.key48')/*审批流程平均时长*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.averageApprovalTime}</h2>
          </div>
        </div>
      </div>
    }
    if (parseInt(params.id) === 33) {
      return (
        <div className='card-ward'>
          <div className='card-item'>
            <div className='header'>
              <div className='title f_left'>
                {messages('data-center.key149')/*待审批单据数量*/}
              </div>
              <div className='tips f_right'/>
            </div>
            <div className="content">
              <h2 className='card-content'>{cardData.allApprovedDocTodoQty}</h2>
            </div>
          </div>
          <div className='card-item'>
            <div className='header'>
              <div className='title f_left'>
                {messages('data-center.key150')/*平均待审批时长*/}
              </div>
              <div className='tips f_right'/>
            </div>
            <div className="content">
              <h2 className='card-content'>{cardData.averageApprovalTodoTime}</h2>
            </div>
          </div>
        </div>
      )
    }
    return <div/>
  }

  showModal = (data) => {
    console.log('showModal', data)
    // this.setState({ visible: true })
  }

  onCancelModal = () => {
    this.setState({ visible: false, giftVisible: false })
  }

  onOpenModal = (record, title) => {
    this.setState({
      modalBusinessCode: record.businessCode,
      modalTitle: title,
      modalInvoiceOid: record.invoiceOid
    }, () => {
      this.setState({ visible: true })
    })
    // console.log("record", record)
  }

  onOpenGiftModal = (record, title) => {
    this.setState({
      giftModalBusinessCode: record.businessCode,
      giftModalTitle: title
    }, () => {
      this.setState({ giftVisible: true })
    })
  }

  render() {
    const { loadingSearchArea, params, data, reportDetail } = this.state;
    let request = {
      id: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
      criteria: params
    }
    return (
      <div className="travel-report-wrap">
        <div className="title-wrap-name">
          {reportDetail.reportName}
        </div>
        {this.renderSearchArea()}
        {this.renderCards()}
        <div className="table-header">
          <div className="table-header-title">
            {!loadingSearchArea && <div style={{
              display: 'inline-block',
              marginRight: '10px',
            }}>
              <ExportModal
                codeCheck={true}
                disabled={data.length < 1}
                type={"btn"}
                btnType={"primary"}
                exportTitle={messages('data-center.key21'/*导出数据*/)}
                exportType="REPORT"
                exportCondition={{
                  "exportType": "REPORT",
                  "reportSearchDTO": request,
                  "command": reportDetail.reportCode
                }}
              />
            </div>}
            <Button onClick={this.goToSetting}>
              {messages('data-center.key22'/*字段设置*/)}
            </Button>
          </div>
        </div>
        {this.renderReportTable()}
        <div>
          <a style={{ fontSize: '14px', paddingBottom: '20px' }} onClick={this.handleBack}>
            <Icon type="rollback" style={{ marginRight: '5px' }}/>
            {messages('common.back')}
          </a>
        </div>
        <TravelModal
          visible={this.state.visible}
          title={this.state.modalTitle}
          onCancel={this.onCancelModal}
          onOk={this.onCancelModal}
          businessCode={this.state.modalBusinessCode}
          invoiceOid={this.state.modalInvoiceOid}
        />
         <TravelGiftModal
          visible={this.state.giftVisible}
          title={this.state.giftModalTitle}
          onCancel={this.onCancelModal}
          onOk={this.onCancelModal}
          businessCode={this.state.giftModalBusinessCode}
        />
      </div>
    )
  }
}

TravelReport.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(TravelReport);
